﻿using AutoMapper;
using ManagementApi.Mvc;
using Modules;
using Modules.Corp;
using Modules.Person;
using PmSoft;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
using static Modules.Person.PersonConstants;

namespace ManagementApi.Models.Person
{
    public class PersonBankEditForm
    {
        /// <summary>
        /// 主键
        ///</summary>
        [Display(Name = "主键")]
        public int? Id { get; set; }

        /// <summary>
        /// 人员身份证号
        /// </summary>
        [Display(Name = "人员身份证号")]
        [Required(ErrorMessage = "{0}不能为空")]
        public string? IdCard { get; set; }

        /// <summary>
        /// 工资卡类型
        /// </summary>
        [Display(Name = "工资卡类型")]
        [Required(ErrorMessage = "{0}不能为空")]
        public 工资卡类型? Type { get; set; }

        /// <summary>
        /// 发放工资银行卡号
        ///</summary>
        [Display(Name = "发放工资银行卡号")]
        [Required(ErrorMessage = "{0}不能为空")]
        [RegularExpression(RegxPatterns.BankNo, ErrorMessage = "银行卡号只能为16-19位数字")]
        public string? CardNo { get; set; }

        /// <summary>
        /// 发放工资银行名称
        ///</summary>
        [Display(Name = "发放工资银行名称")]
        [Required(ErrorMessage = "{0}不能为空")]
        public string? BankName { get; set; }

        /// <summary>
        /// 发放工资卡银行联号
        ///</summary>
        [Display(Name = "发放工资卡银行联号")]
        public string? BankLinkNo { get; set; }

        /// <summary>
        /// 发放工资卡银行 参考银行代码字典表
        ///</summary>
        [Display(Name = "发放工资卡银行")]
        public string? BankCode { get; set; }

        /// <summary>
        /// 银行地址
        ///</summary>
        [Display(Name = "银行地址")]
        public string? BankAddress { get; set; }

        public int? CorpId { get; set; }

        public string? CorpName { get; set; }

        public string? PersonName { get; set; }
    }

    public static class PersonBankExtensions
    {
        public static PersonBankEditForm AsForm(this PersonBank entity, int corpId)
        {
            var mapper = ServiceAccessor.GetService<IMapper>();
            PersonBankEditForm form = new();
            mapper.Map(entity, form);

            var personService = ServiceAccessor.GetService<PersonService>();
            var personInfo = personService.GetPersonByCardNo(entity.IdCard);
            form.PersonName = personInfo?.Name;
            form.IdCard = personInfo?.CardNumber;
            var corpService = ServiceAccessor.GetService<CorpService>();
            CorpInfo? corpInfo = corpService.GetCorpInfo(corpId);
            if (corpInfo != null)
            {
                form.CorpName = corpInfo.Name;
                form.CorpId = corpInfo.CorpId;
            }
            return form;
        }
    }
}